import time
import serial

def fota_upgrade(serial_port, ftp_address):
    """
    实现FOTA升级函数

    :param serial_port: 串口实例，需要有write和readline方法
    :param ftp_address: FTP地址，格式为 "ftp://用户名:密码@ftp地址/文件路径"
    :return: 升级是否成功
    """
    # 发送AT+SGSW命令以获取当前版本
    serial_port.write(b'AT+SGSW\r\n')
    time.sleep(1)  # 等待一段时间以获取返回
    current_version = serial_port.readline().decode().strip()
    print(f"当前版本: {current_version}")
    
    # 发送AT+QFOTADL=ftp地址命令以开始升级
    serial_port.write(f'AT+QFOTADL={ftp_address}\r\n'.encode())
    success = False
    
    while True:
        response = serial_port.readline().decode().strip()
        print(f"模块响应: {response}")
        
        if "FTPSTART" in response:
            print("升级开始...")
        elif "FTPEND,0" in response:
            print("升级成功...")
            success = True
            break
        elif "AT READY" in response:
            print("模组已开机，等待版本确认...")
            # 发送AT+SGSW命令以获取新版本
            serial_port.write(b'AT+SGSW\r\n')
            time.sleep(1)  # 等待一段时间以获取返回
            new_version = serial_port.readline().decode().strip()
            print(f"新版本: {new_version}")
            if new_version != current_version:
                print("版本确认，FOTA升级成功...")
                success = True
                break
        elif "ERROR" in response:
            print("升级过程中出错...")
            break

    return success

def fota_test():
    # 获取所有可用的串口
    available_ports = serial.tools.list_ports.comports()
    serial_ports = []

    # 连接到每个串口并发送AT命令以检查响应
    for port in available_ports:
        try:
            ser = serial.Serial(port.device, 115200, timeout=5)
            ser.write(b'AT\r\n')
            response = ser.readline().decode().strip()
            if "OK" in response:
                print(f"端口 {port.device} 有响应，保留连接...")
                serial_ports.append(ser)
            else:
                print(f"端口 {port.device} 无响应，删除连接...")
                ser.close()
        except Exception as e:
            print(f"连接端口 {port.device} 时出错: {e}")

    # 创建两个FTP地址
    ftp_address_A = "ftp://test:123456@116.247.69.94:13006/CTWing_CTL03_RV_Rev20_V01-V02"
    ftp_address_B = "ftp://test:123456@116.247.69.94:13006/CTWing_CTL03_RV_Rev20_V01-V02"

    # 循环10次进行FOTA升级测试
    test_results = []
    for i in range(10):
        print(f"测试循环 {i+1} 开始...")
        for ser in serial_ports:
            print(f"在端口 {ser.name} 上进行FOTA升级...")
            success_B = fota_upgrade(ser, ftp_address_B)
            success_A = fota_upgrade(ser, ftp_address_A)
            test_results.append((ser.name, i+1, success_B, success_A))
        print(f"测试循环 {i+1} 结束...\n")

    # 输出测试结果
    print("测试结果汇总:")
    for result in test_results:
        print(f"端口: {result[0]}, 循环: {result[1]}, 升级B: {'成功' if result[2] else '失败'}, 升级A: {'成功' if result[3] else '失败'}")

# 调用测试函数
fota_test()
